package com.hmall.item.web;

import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
@Slf4j
public class ItemController {

    @Autowired
    private IItemService itemService;

    /**
     * 商品的分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public PageDTO getPage(@RequestParam(value = "page",defaultValue = "1") Integer pageNum,
                           @RequestParam(value = "size",defaultValue = "5")Integer pageSize){
        log.info("商品的分页查询,请求参数为pageNum={}，pageSize={}",pageNum,pageSize);
        //调用业务层
        PageDTO pageDTO=itemService.getPage(pageNum,pageSize);
        //返回结果
        return pageDTO;
    }

    /**
     * 新增商品
     * @param item
     */

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping
    public void addItem(@RequestBody Item item){
        //打印日志
        log.info("添加商品，请求参数为{}",item);
        rabbitTemplate.convertAndSend("simple.queue","hasUpdate");
        itemService.save(item);
    }

    /**
     * 根据id删除商品
     * @param id
     */
   @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        log.info("根据id删除商品");
       itemService.deleteById(id);
   }

    /**
     * 商品上下架
     * @param id
     * @param status
     */
   @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable Long id ,
                                 @PathVariable Integer status){
       log.info("商品上下架");
       itemService.updateItemStatus(id,status);
   }

    /**
     * 修改商品
     * @param item
     */
   @PutMapping
    public void updateItem(@RequestBody Item item){
        log.info("修改商品，请求参数为{}",item);
        itemService.updateItem(item);
   }


    /**
     * 根据id查询
     * @param id
     * @return
     */
   @GetMapping("/{id}")
    public Item save(@PathVariable Long id){
       return itemService.getById(id);
   }


    /**
     * 扣减库存
     * @param itemId
     * @param num
     */
   @PutMapping("/stock/{itemId}/{num}")
    public void updateStock(@PathVariable Long itemId,
                            @PathVariable Integer num
                            ){
       itemService.updateStock(itemId,num);
   }

}
